#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
#Copyright (c) 2009 Timothe Faudot

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""

"""
This class allows tracking of a template using the official OpenCV wrappers"""


#openCV
from opencv import *
from opencv.cv import *
from opencv.highgui import *

#others
from math import fabs

class CvPad:
    """
    Class handling the OpenCV methods calls
    """
    def __init__(self):
        self.cap = cvCreateCameraCapture(-1)
        self.min_loc = None
        self.max_loc = None
        self.min_val = 0.0
        self.max_val = 0.0
        dst_size = None
        self.src_img = None
        self.tplt_img = None
        self.resultMatch = None
        self.thumbWidth=320
        self.thumbHeight=240

    def setTemplateImage(self, path):
        """
        Set a custom image from a file to be used as a template
        """
        self.tplt_img = cvLoadImage(path, CV_LOAD_IMAGE_COLOR)

    def setThumbDefaultSize(self, w, h):
        """
        Sets the size of the requested opencv image
        """
        self.thumbWidth = w
        self.thumbHeight = h

    def nextFrame(self):
        """Step to the next frame of the capture"""
        self.src_img = cvQueryFrame(self.cap)
        cvCvtColor(self.src_img, self.src_img, CV_BGR2RGB)

    def getThumb(self):
        """
        Returns a image of the size given by the call to setThumbDefaultSize
        """
        imgThumb = cvCreateImage(cvSize(self.thumbWidth, self.thumbHeight), 8, 3)
        cvResize(self.src_img, imgThumb, CV_INTER_LINEAR)
        
        return imgThumb

    def locateTemplate(self):
        """Locates the template on the current image"""
        cvMatchTemplate(self.src_img, self.tplt_img, self.resultMatch, CV_TM_CCOEFF_NORMED)
        [self.min_val, self.max_val, self.min_loc, self.max_loc] = cvMinMaxLoc(self.resultMatch, None)
        cvMinMaxLoc(self.resultMatch, None)

        return self.max_loc.x+self.tplt_img.width/2,\
                self.max_loc.y+self.tplt_img.height/2

    def showTemplate(self):
        """shows the real sized template image (using the opencv gui)"""
        cvNamedWindow("template", CV_WINDOW_AUTOSIZE)
        cvShowImage("template", self.tplt_img)
        cvWaitKey(10)

    def setTemplate(self, x1, y1, x2, y2):
        """Sets the template as selected by the user"""
        cvReleaseImage(self.tplt_img)
        #the coords received as parameters are relative to the size of the outputpanel
        #so we have to arrange that to match the real size of the camera input
        #or we won't get the real template...
        x1=x1*self.src_img.width/self.thumbWidth
        x2=x2*self.src_img.width/self.thumbWidth
        y1=y1*self.src_img.height/self.thumbHeight
        y2=y2*self.src_img.height/self.thumbHeight
        #print "the size of the rectangle will be:"
        self.tplt_img = cvCloneImage(cvGetSubRect(self.src_img, cvRect(x1, y1, int(fabs(x2-x1)), int(fabs(y2-y1)))))
        
        self.resultMatch = cvCreateImage(cvSize(self.src_img.width - self.tplt_img.width + 1,
                                            self.src_img.height - self.tplt_img.height + 1),
                                     IPL_DEPTH_32F, 1)